package com.ruoyi.yljf.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateTime;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.yljf.domain.ScoreType;
import com.ruoyi.yljf.domain.User;
import com.ruoyi.yljf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.mapper.UserScoreRecordMapper;
import com.ruoyi.yljf.domain.UserScoreRecord;
import com.ruoyi.yljf.service.IUserScoreRecordService;

import javax.annotation.Resource;

/**
 * 用户积分明细Service业务层处理
 * 
 * @author TAT
 * @date 2025-04-11
 */
@Service
public class UserScoreRecordServiceImpl extends ServiceImpl<UserScoreRecordMapper, UserScoreRecord> implements IUserScoreRecordService {
    @Resource
    private UserScoreRecordMapper userScoreRecordMapper;
    @Resource
    private UserMapper userMapper;
    
    /**
     * 查询用户积分明细列表
     * 
     * @param userScoreRecord 用户积分明细
     * @return 用户积分明细
     */
    @Override
    public List<UserScoreRecord> selectUserScoreRecordList(UserScoreRecord userScoreRecord) {
    	LambdaQueryWrapper<UserScoreRecord> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotNull(userScoreRecord.getUserId())) {
			queryWrapper.eq(UserScoreRecord::getUserId, userScoreRecord.getUserId());
		}
        if (StringUtils.isNotNull(userScoreRecord.getScore())) {
			queryWrapper.eq(UserScoreRecord::getScore, userScoreRecord.getScore());
		}
        if (StringUtils.isNotEmpty(userScoreRecord.getType())) {
			queryWrapper.eq(UserScoreRecord::getType, userScoreRecord.getType());
		}
        if (StringUtils.isNotEmpty(userScoreRecord.getSource())) {
			queryWrapper.eq(UserScoreRecord::getSource, userScoreRecord.getSource());
		}
        return userScoreRecordMapper.selectList(queryWrapper);
    }

    @Override
    public void adduserScore(User user, ScoreType scoreType) {
        user.setScore(user.getScore()+scoreType.getScore());
        user.setTotalScore(user.getTotalScore() + scoreType.getScore());
        userMapper.updateById(user);
        UserScoreRecord userScoreRecord = new UserScoreRecord(null, user.getUserId(), scoreType.getScore(), scoreType.getType(), "0", DateTime.now(),0L);
        this.save(userScoreRecord);
    }

    @Override
    public void subtractScore(User user, ScoreType scoreType) {
        Integer score = user.getScore() - scoreType.getScore();
        if(score < 0) score = 0;
        user.setScore(score);
        userMapper.updateById(user);
        UserScoreRecord userScoreRecord = new UserScoreRecord(null, user.getUserId(), scoreType.getScore(), scoreType.getType(), "0", DateTime.now(), 0L);
        this.save(userScoreRecord);
    }
}
